
class Op{
    constructor(){
        this.getData();
    }
    // 获取数据
    async getData(){
        let {data,status}=await axios.get('http://localhost:8888/goods/list');
        console.log(data);
        if(status!=200)throw new Error('出错了,老铁睁睁眼!');
        if (data.code == 0) {
            //过期跳转登录页面
            location.assign('./login.html?returnUrl=./cart.html');
        }
        if(data.code==1){
        let html='';
        data.list.forEach(ele => {
            console.log(ele);
            html += `
            <div class="oned ">
                <a href="./detail.html?id=${ele.goods_id}" class="one">
                    <img src="${ele.img_big_logo}" alt="">
                </a>
                <a href="#none" class="two">
                    <div>${ele.title}</div>
                </a>
                <a href="#none" class="there">
                    <h2>${ele.price}</h2>
                </a>
                <a href="#none" class="for">
                    <button onclick="Op.nowBuy(${ele.goods_id})">加入购物车</button>
            </a>
            </div>
        `; 
            
        });
        
        document.querySelector('.xuanran').innerHTML=html;
        document.querySelector('.xuanran').innerHTML+=html;
        document.querySelector('.xuanran').innerHTML+=html;
        document.querySelector('.xuanran').innerHTML+=html;
    }
    }
    //加购物车
    static  nowBuy(goodsId){
        let token=localStorage.getItem('token');
        if(!token)location.href='./login.html?index.html';
        //用户IDtoken中用户id
        let userId=localStorage.getItem('user_id');
        let param = `id=${userId}&goodsId=${goodsId}`;
        console.log(param);
        //发送请求
        //请求头
        axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';
        axios.defaults.headers.common['Authorization'] = token;
        axios.post('http://localhost:8888/cart/add', param).then(res=>{
            let { status, data } = res;
            if (status != 200) throw new Error('眼睛是个好东西!');
            if (data.code == 0) location.href = './login.html?index.html';
            layer.confirm('钱不是花了,而是换成另一种方式陪着你...',{
                btn: ['不败家了', '继续败家'] 
                }, function (){
                    location.href = './cart.html';
                });
        })
    }
}
new Op;
